from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Table, TableStyle
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_CENTER
from reportlab.lib import colors
import os

pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.ttf'))

styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='Chinese', fontName='SimHei', fontSize=12, leading=20))
styles.add(ParagraphStyle(name='MyTitle', fontName='SimHei', fontSize=20, alignment=TA_CENTER, spaceAfter=20))
styles.add(ParagraphStyle(name='SectionHeader', fontName='SimHei', fontSize=14, spaceAfter=10,
                          textColor=colors.HexColor("#003366")))


def create_pdf(output_path, scores, suggestions, radar_chart_path, resume_text, final_score):
    doc = SimpleDocTemplate(output_path, pagesize=A4,
                            rightMargin=2 * cm, leftMargin=2 * cm,
                            topMargin=2 * cm, bottomMargin=2 * cm)
    content = []

    # 标题
    content.append(Paragraph("AI 智能面试能力评估报告", styles["MyTitle"]))
    content.append(Spacer(1, 12))

    # 简历摘要
    content.append(Paragraph("一、简历摘要", styles["SectionHeader"]))
    content.append(Paragraph(resume_text.replace("\n", "<br/>"), styles["Chinese"]))
    content.append(Spacer(1, 12))

    # 能力评分（表格展示）
    content.append(Paragraph("二、核心能力评分", styles["SectionHeader"]))
    data = [["能力维度", "评分（满分100）"]] + [[k, f"{v:.1f}"] for k, v in scores.items()]
    table = Table(data, colWidths=[6 * cm, 6 * cm])
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor("#eeeeee")),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.HexColor("#000000")),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, -1), 'SimHei'),
        ('FONTSIZE', (0, 0), (-1, -1), 12),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey)
    ]))
    content.append(table)
    content.append(Spacer(1, 12))

    # 插入雷达图，确保标题和图都在同一新页
    if os.path.exists(radar_chart_path):
        content.append(PageBreak())  # 这里新增分页
        content.append(Paragraph("三、能力雷达图", styles["SectionHeader"]))
        content.append(Image(radar_chart_path, width=14 * cm, height=14 * cm))
        content.append(Spacer(1, 12))


    # 面试建议
    content.append(PageBreak())
    content.append(Paragraph("四、面试反馈建议", styles["SectionHeader"]))
    for i, s in enumerate(suggestions, 1):
        content.append(Paragraph(f"{i}. {s}", styles["Chinese"]))
    content.append(Spacer(1, 12))

    # 综合评分
    content.append(Paragraph("五、综合评分", styles["SectionHeader"]))
    content.append(Paragraph(f"⭐ 最终面试评分：<b>{final_score} / 100</b>", styles["Chinese"]))

    if final_score >= 85:
        comment = "表现优异，推荐录用。"
    elif final_score >= 70:
        comment = "表现良好，可考虑进入下一轮评估。"
    elif final_score >= 60:
        comment = "部分能力存在不足，建议继续培训后再申请。"
    else:
        comment = "能力匹配度较低，不建议进入下一轮。"

    content.append(Paragraph(f"综合评价：{comment}", styles["Chinese"]))

    doc.build(content)
